/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getlength(ListNode* head) {
        ListNode* p = head;
        int n = 0;
        while (p) {
            p = p->next;
            n++;
        }
        return n;
    }

    ListNode* rotateRight(ListNode* head, int k) {
        int len = 0;
        len = getlength(head);
        if (len == 1 || len == 0)
            return head;
        ListNode *p = head, *q = head;
        k %= len;
        if (k == 0)
            return head;
        int i = 0;
        for (i = 0; i <= k; i++)
            p = p->next;

        while (p)
            q = q->next, p = p->next;

        p = q->next;
        q->next = nullptr;
        q = p;
        while (p->next)
            p = p->next;
        p->next = head;
        return q;
    }
};